package edu.pitt.cs.cs2410pj2.util;
/**
 * Util class,deals with the byte str stuff
 * @author zhangfan
 *
 */
public class ByteStrOperator {
	public static String decToBinary2(int val) {
		String str = "";
		while(val!=0) {
			int digit = val%2;
			val = val>>1;
			str+=digit;
		}
		int zeroLength = 4 - str.length();
		String reverse = "";
		for(int i = 0;i<zeroLength;i++) {
			reverse+="0";
		}
		for(int i = str.length()-1;i>=0;i--) {
			reverse += str.charAt(i);
		}
		
		return reverse;
	}
	
	public static String hexToBinary(String hexStr) {
		hexStr = hexStr.substring(2);
		if(hexStr.length()<8) {
			int extraZero = 8-hexStr.length();
			for(int i = 0;i<extraZero;i++) {
				hexStr="0"+hexStr;
			}
		}
		String binaryStr = "";
		int len = hexStr.length();
		for(int i = 0;i<len;i++) {
			binaryStr += decToBinary2(Character.getNumericValue(hexStr.charAt(i)));
		}
		return binaryStr;
	}
	
	
	//Get the byte str of a specified location out
	public static String getByteFromHex(String hexStr,int i,int j) {
		//int val = hexToDec(hexStr);
		//String binaryStr = decToBinary(val);
		String binaryStr = hexToBinary(hexStr);
		return binaryStr.substring(i,j+1);
	}
	
	//Change 0x11 to 17, for example
	public static int hexToDec(String hexStr) {
		hexStr = hexStr.substring(2);
		int len = hexStr.length();
		int power = 0;
		int hexVal = 0;
		for(int i = len-1;i>=0;i--) {
			hexVal += Math.pow(16, power)*Character.getNumericValue(hexStr.charAt(i));
			power++;
		}
		return hexVal;
	}
	
	//Change the decimal value to a 32 digit binary str
	public static String decToBinary(int val) {
		String str = "";
		while(val!=0) {
			int digit = val%2;
			val = val>>1;
			str+=digit;
		}
		int zeroLength = 32 - str.length();
		String reverse = "";
		for(int i = 0;i<zeroLength;i++) {
			reverse+="0";
		}
		for(int i = str.length()-1;i>=0;i--) {
			reverse += str.charAt(i);
		}
		
		return reverse;
	}
	
	//Change 0011 to 3, for example
	public static int byteStrToDec(String byteStr) {
		int len = byteStr.length();
		int power = 0;
		int byteVal = 0;
		for(int i = len-1;i>=0;i--) {
			byteVal += Math.pow(2, power)*Character.getNumericValue(byteStr.charAt(i));
			power++;
		}
		return byteVal;
	}
	
	public static void main(String[] args) {
		System.out.println(decToBinary(11));
		System.out.println(byteStrToDec("1010"));
		System.out.println(hexToDec("0x1B"));
		System.out.println(getByteFromHex("0x0000001b",0,31));
		System.out.println(getByteFromHex("0x0000001B",0,31));
	}
}
